<template>
    <div class="coupon-list">
        <!-- 搜索栏 -->
        <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="优惠券名称">
                <el-input v-model="queryParams.name" placeholder="请输入优惠券名称" clearable />
            </el-form-item>
            <el-form-item label="优惠券类型">
                <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
                    <el-option label="减免金额" value="AMOUNT" />
                    <el-option label="折扣券" value="DISCOUNT" />
                    <el-option label="全免券" value="FREE" />
                    <el-option label="减时券" value="TIME" />
                </el-select>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                    <el-option label="启用" value="ENABLED" />
                    <el-option label="禁用" value="DISABLED" />
                </el-select>
            </el-form-item>
            <el-form-item label="有效期">
                <el-date-picker v-model="queryParams.dateRange" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
                <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 操作栏 -->
        <div class="operation-bar">
            <el-button type="primary" @click="handleCreate">创建优惠券</el-button>
        </div>

        <!-- 表格 -->
        <el-table :data="couponList" border @selection-change="handleSelectionChange" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="优惠券名称" show-overflow-tooltip />
            <el-table-column prop="type" label="类型">
                <template slot-scope="scope">
                    <el-tag :type="getTypeTagType(scope.row.type)">
                        {{ formatCouponType(scope.row.type) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="value" label="面值">
                <template slot-scope="scope">
                    <span v-if="scope.row.type === 'DISCOUNT'">{{ scope.row.value }}折</span>
                    <span v-else-if="scope.row.type === 'AMOUNT'">￥{{ scope.row.value }}</span>
                    <span v-else-if="scope.row.type === 'TIME'">{{ scope.row.value }}小时</span>
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column label="有效期" width="240">
                <template slot-scope="scope">
                    <el-tooltip :content="getValidityStatus(scope.row)" placement="top">
                        <span :class="{ 'expired': isExpired(scope.row) }">
                            {{ scope.row.validFrom }} 至 {{ scope.row.validTo }}
                        </span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column label="领取情况" width="180">
                <template slot-scope="scope">
                    <el-progress :percentage="calculateProgress(scope.row)" :status="getProgressStatus(scope.row)" />
                    <div class="quantity-info">
                        {{ scope.row.receivedQuantity }}/{{ scope.row.totalQuantity }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 'ENABLED' ? 'success' : 'info'">
                        {{ scope.row.status === 'ENABLED' ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" :type="scope.row.status === 'ENABLED' ? 'warning' : 'success'"
                        @click="handleStatusChange(scope.row)">
                        {{ scope.row.status === 'ENABLED' ? '禁用' : '启用' }}
                    </el-button>
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button size="mini" type="info" @click="handleViewDetails(scope.row)">
                        详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination :current-page="page.current" :page-size="page.size" :total="page.total"
            :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
            @current-change="handlePageChange" @size-change="handleSizeChange" />

        <!-- 创建优惠券对话框 -->
        <el-dialog :title="dialogType === 'create' ? '创建优惠券' : '编辑优惠券'" :visible.sync="dialogVisible" width="600px">
            <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
                <el-form-item label="优惠券名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入优惠券名称" />
                </el-form-item>

                <el-form-item label="优惠券类型" prop="type">
                    <el-radio-group v-model="formData.type">
                        <el-radio label="AMOUNT">减免金额</el-radio>
                        <el-radio label="DISCOUNT">折扣券</el-radio>
                        <el-radio label="FREE">全免券</el-radio>
                        <el-radio label="TIME">减时券</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="优惠券面值" prop="value">
                    <el-input-number v-model="formData.value" :precision="formData.type === 'DISCOUNT' ? 1 : 2"
                        :min="formData.type === 'DISCOUNT' ? 0.1 : 0" :max="formData.type === 'DISCOUNT' ? 9.9 : 999999"
                        :step="formData.type === 'DISCOUNT' ? 0.1 : 1">
                        <template #append v-if="formData.type === 'DISCOUNT'">折</template>
                        <template #append v-else-if="formData.type === 'AMOUNT'">元</template>
                        <template #append v-else-if="formData.type === 'TIME'">小时</template>
                    </el-input-number>
                    <span class="tips" v-if="formData.type === 'DISCOUNT'">（如：7.5代表7.5折）</span>
                </el-form-item>

                <el-form-item label="有效期" prop="validDate">
                    <el-date-picker v-model="formData.validDate" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
                        :default-time="['00:00:00', '23:59:59']" />
                </el-form-item>

                <el-form-item label="发放总量" prop="totalQuantity">
                    <el-input-number v-model="formData.totalQuantity" :min="1" :precision="0" placeholder="请输入发放总量" />
                </el-form-item>

                <el-form-item label="每人限领" prop="perUserLimit">
                    <el-input-number v-model="formData.perUserLimit" :min="1" :max="formData.totalQuantity"
                        :precision="0" placeholder="请输入每人限领数量" />
                </el-form-item>

                <el-form-item label="使用说明" prop="description">
                    <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入优惠券使用说明" />
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogType === 'create' ? handleSubmit() : handleUpdate()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCoupon, addCoupon, updateCoupon, updateCouponStatus } from '@/api/coupon/coupon'

export default {
    name: 'CouponList',
    data() {
        return {
            // 查询参数
            queryParams: {
                name: '',
                type: '',
                status: '',
                dateRange: []
            },
            // 选中的记录ID数组
            selectedIds: [],
            // 加载状态
            loading: false,
            // 列表数据
            couponList: [],
            page: {
                current: 1,
                size: 10,
                total: 0
            },
            // 对话框控制
            dialogVisible: false,
            // 表单数据
            formData: {
                name: '',
                type: 'AMOUNT',
                value: 0,
                validDate: [],
                totalQuantity: 1,
                perUserLimit: 1,
                description: ''
            },
            // 表单验证规则
            rules: {
                name: [
                    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '请选择优惠券类型', trigger: 'change' }
                ],
                value: [
                    { required: true, message: '请输入优惠券面值', trigger: 'blur' }
                ],
                validDate: [
                    { required: true, message: '请选择有效期', trigger: 'change' }
                ],
                totalQuantity: [
                    { required: true, message: '请输入发放总量', trigger: 'blur' }
                ],
                perUserLimit: [
                    { required: true, message: '请输入每人限领数量', trigger: 'blur' }
                ],
                description: [
                    { max: 200, message: '最多输入200个字符', trigger: 'blur' }
                ]
            },
            // 添加对话框类型
            dialogType: 'create', // 'create' 或 'edit'
        }
    },
    created() {
        this.fetchCouponList()
    },
    methods: {
        formatCouponType(type) {
            const typeMap = {
                'AMOUNT': '减免金额',
                'DISCOUNT': '折扣券',
                'FREE': '全免券',
                'TIME': '减时券'
            }
            return typeMap[type] || type
        },
        async fetchCouponList() {
            try {
                this.loading = true
                // 处理日期范围
                let dateRangeStr = ''
                if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
                    dateRangeStr = this.queryParams.dateRange.join('至')
                }

                const response = await listCoupon({
                    pageNum: this.page.current,
                    pageSize: this.page.size,
                    name: this.queryParams.name,
                    type: this.queryParams.type,
                    status: this.queryParams.status,
                    dateRange: dateRangeStr
                })
                this.couponList = response.data.records
                this.page.total = response.data.total
            } catch (error) {
                this.$message.error('获取优惠券列表失败')
            } finally {
                this.loading = false
            }
        },
        handleCreate() {
            this.dialogType = 'create'
            this.dialogVisible = true
            // 重置表单数据
            this.formData = {
                name: '',
                type: 'AMOUNT',
                value: 0,
                validDate: [],
                totalQuantity: 1,
                perUserLimit: 1,
                description: ''
            }
            // 确保在 DOM 更新后再重置表单验证状态
            this.$nextTick(() => {
                if (this.$refs.form) {
                    this.$refs.form.resetFields()
                }
            })
        },
        async handleSubmit() {
            try {
                await this.$refs.form.validate()
                const [validFrom, validTo] = this.formData.validDate
                const submitData = {
                    ...this.formData,
                    validFrom: validFrom,
                    validTo: validTo
                }
                delete submitData.validDate

                await addCoupon(submitData)
                this.$message.success('创建成功')
                this.dialogVisible = false
                this.fetchCouponList()
            } catch (error) {
                this.$message.error('创建失败')
            }
        },
        async handleStatusChange(row) {
            try {
                await updateCouponStatus({
                    id: row.id,
                    status: row.status === 'ENABLED' ? 'DISABLED' : 'ENABLED'
                })
                this.$message.success('状态更新成功')
                this.fetchCouponList()
            } catch (error) {
                this.$message.error('状态更新失败')
            }
        },
        handlePageChange(page) {
            this.page.current = page
            this.fetchCouponList()
        },
        handleSizeChange(size) {
            this.page.size = size
            this.fetchCouponList()
        },
        // 处理查询
        handleQuery() {
            this.page.current = 1
            this.fetchCouponList()
        },
        // 重置查询
        resetQuery() {
            this.queryParams = {
                name: '',
                type: '',
                status: '',
                dateRange: []
            }
            this.handleQuery()
        },
        // 获取类型标签样式
        getTypeTagType(type) {
            const typeMap = {
                'AMOUNT': 'primary',
                'DISCOUNT': 'warning',
                'FREE': 'success',
                'TIME': 'info'
            }
            return typeMap[type] || ''
        },
        // 计算领取进度
        calculateProgress(row) {
            return Math.round((row.receivedQuantity / row.totalQuantity) * 100)
        },
        // 获取进度条状态
        getProgressStatus(row) {
            const percentage = this.calculateProgress(row)
            if (percentage >= 90) return 'exception'
            if (percentage >= 80) return 'warning'
            return ''
        },
        // 检查是否过期
        isExpired(row) {
            return new Date(row.validTo) < new Date()
        },
        // 获取有效期状态提示
        getValidityStatus(row) {
            if (this.isExpired(row)) return '已过期'
            const now = new Date()
            const validTo = new Date(row.validTo)
            const daysLeft = Math.ceil((validTo - now) / (1000 * 60 * 60 * 24))
            return `剩余 ${daysLeft} 天`
        },
        // 处理表格选择
        handleSelectionChange(selection) {
            this.selectedIds = selection.map(item => item.id)
        },
        // 添加编辑方法
        handleEdit(row) {
            this.dialogType = 'edit'
            this.dialogVisible = true
            // 转换日期格式
            const validDate = [row.validFrom, row.validTo]
            this.formData = {
                ...row,
                validDate
            }
        },
        // 添加更新方法
        async handleUpdate() {
            try {
                await this.$refs.form.validate()
                const [validFrom, validTo] = this.formData.validDate
                const submitData = {
                    ...this.formData,
                    validFrom,
                    validTo
                }
                delete submitData.validDate

                await updateCoupon(submitData)
                this.$message.success('更新成功')
                this.dialogVisible = false
                this.fetchCouponList()
            } catch (error) {
                this.$message.error('更新失败')
            }
        },
    }
}
</script>

<style scoped>
.coupon-list {
    padding: 20px;
}

.search-form {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-bar {
    margin-bottom: 20px;
}

.expired {
    color: #F56C6C;
}

.quantity-info {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
    text-align: center;
}

.el-tag {
    margin-right: 5px;
}

.el-button+.el-button {
    margin-left: 5px;
}

.tips {
    color: #909399;
    font-size: 12px;
    margin-left: 10px;
}

.el-radio-group {
    width: 100%;
}

.el-radio {
    margin-right: 30px;
    margin-bottom: 10px;
}

.el-input-number {
    width: 220px;
}
</style>